const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 游戏对象
const game = {
  cleared: false,
  gameActive: true,
  paddle: {
    width: 100,
    height: 15,
    x: canvas.width/2 - 50,
    y: canvas.height - 30,
    speed: 8
  },
  ball: {
    radius: 8,
    x: canvas.width/2,
    y: canvas.height - 50,
    dx: 4,
    dy: -4,
    active: false
  },
  bricks: [],
  score: 0,
  lives: 3,
  difficulty: 1,
  lastDifficultyUpdate: Date.now(),
  powerups: []
};

// 初始化砖块阵列
function initBricks() {
  const rows = 6;
  const cols = 10;
  const padding = 2;
  const brickWidth = canvas.width/cols - padding;
  
  for(let i=0; i<rows; i++) {
    game.bricks[i] = [];
    for(let j=0; j<cols; j++) {
      game.bricks[i][j] = {
        x: j*(brickWidth + padding),
        y: i*25 + 50,
        width: brickWidth,
        height: 20,
        color: `hsl(${Math.random()*360}, 50%, 50%)`,
        active: true
      };
    }
  }
}

// 键盘控制
const keys = {};
document.addEventListener('keydown', e => {
  keys[e.key] = true;
  if(e.key === ' ') game.ball.active = true;
});
document.addEventListener('keyup', e => keys[e.key] = false);

// 碰撞检测
function collisionDetection(obj1, obj2) {
  return obj1.x < obj2.x + obj2.width &&
         obj1.x + obj1.width > obj2.x &&
         obj1.y < obj2.y + obj2.height &&
         obj1.y + obj1.height > obj2.y;
}

// 游戏循环
function update() {
  // 挡板移动
  if(keys.ArrowLeft && game.paddle.x > 0) {
    game.paddle.x -= game.paddle.speed;
  }
  if(keys.ArrowRight && game.paddle.x < canvas.width - game.paddle.width) {
    game.paddle.x += game.paddle.speed;
  }

  // 小球运动
  if(game.ball.active) {
    game.ball.x += game.ball.dx;
    game.ball.y += game.ball.dy;

    // 边界碰撞
    if(game.ball.x < 0 || game.ball.x > canvas.width) game.ball.dx *= -1;
    if(game.ball.y < 0) game.ball.dy *= -1;

    // 挡板碰撞
    if(collisionDetection({
      x: game.ball.x - game.ball.radius,
      y: game.ball.y - game.ball.radius,
      width: game.ball.radius*2,
      height: game.ball.radius*2
    }, game.paddle)) {
      const hitPos = (game.ball.x - game.paddle.x) / game.paddle.width;
      game.ball.dx = 5 * (hitPos - 0.5) * 2;
      game.ball.dy = -Math.abs(game.ball.dy);
      game.ball.y = game.paddle.y - game.ball.radius;
    }

    // 砖块碰撞
    let activeBricks = 0;
game.bricks.forEach(row => {
  row.forEach(brick => {
    if(brick.active) {
      activeBricks++;
      if(collisionDetection({
        x: game.ball.x - game.ball.radius,
        y: game.ball.y - game.ball.radius,
        width: game.ball.radius*2,
        height: game.ball.radius*2
      }, brick)) {
        brick.active = false;
        game.score += 10;
        game.ball.dy *= -1;
        activeBricks--;
      }
    }
  });
});

if(activeBricks === 0) {
  game.cleared = true;
  game.gameActive = false;
}

    // 球落地检测
    if(game.ball.y > canvas.height) {
      game.lives--;
      if(game.lives <= 0) {
        game.gameActive = false;
      }
      resetBall();
    }
  }

  // 难度系统
  if(Date.now() - game.lastDifficultyUpdate > 30000) {
    game.difficulty = Math.min(5, game.difficulty + 1);
    game.ball.dx *= 1.2;
    game.ball.dy *= 1.2;
    game.lastDifficultyUpdate = Date.now();
  }
}

function resetBall() {
  game.ball.x = canvas.width/2;
  game.ball.y = canvas.height - 50;
  game.ball.dx = 4;
  game.ball.dy = -4;
  game.ball.active = false;
}

// 渲染
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // 游戏结束提示
  if(!game.gameActive) {
    ctx.fillStyle = 'white';
    ctx.font = '48px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(game.cleared ? '恭喜通关!' : '游戏结束', canvas.width/2, canvas.height/2);
    ctx.font = '24px Arial';
    ctx.fillText('点击空格重新开始', canvas.width/2, canvas.height/2 + 50);
    return;
  }

  // 绘制挡板
  ctx.fillStyle = '#2196F3';
  ctx.fillRect(game.paddle.x, game.paddle.y, game.paddle.width, game.paddle.height);

  // 绘制小球
  ctx.beginPath();
  ctx.arc(game.ball.x, game.ball.y, game.ball.radius, 0, Math.PI*2);
  ctx.fillStyle = '#fff';
  ctx.fill();

  // 绘制砖块
  game.bricks.forEach(row => {
    row.forEach(brick => {
      if(brick.active) {
        ctx.fillStyle = brick.color;
        ctx.fillRect(brick.x, brick.y, brick.width, brick.height);
      }
    });
  });

  // 更新界面信息
  document.querySelector('.score').textContent = `分数: ${game.score}`;
  document.querySelector('.difficulty span:first-child').textContent = `难度: ${game.difficulty}`;
  document.querySelector('.lives').innerHTML = '生命: ' + '❤️'.repeat(game.lives);
}

// 启动游戏
function gameLoop() {
  if(game.lives > 0 && !game.cleared) {
    update();
    draw();
    requestAnimationFrame(gameLoop);
  }
}

initBricks();
gameLoop();